package com.linkmed.storage.service.impl;

import com.linkmed.storage.constant.CommonConstant;
import com.linkmed.storage.model.FilePojo;
import com.linkmed.storage.service.FileService;
import com.linkmed.storage.utils.StorageFileUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.thymeleaf.util.DateUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class FileServiceImpl implements FileService {

    private static Logger logger = LoggerFactory.getLogger(FileServiceImpl.class);

    @Autowired
    private StorageFileUtil storageFileUtil;
    @Override
    public List<FilePojo> getList(FilePojo pojo) {
        List<FilePojo> filePojos = new ArrayList<>();
        List<String> list = storageFileUtil.listHosipital(pojo.getDirIds());
        if(null != list && list.size()>0){
            for (String str : list){
                FilePojo filePojo = new FilePojo();
                String names [] = str.split("/");
                if(names.length>0){
                    String name = names[names.length-1];
                    filePojo.setName(name);
                }

                filePojo.setId(str);
                if(str.indexOf(".")>0 && !str.substring(str.length()-1,str.length()).equals("/")){
                    String [] temp = str.split("\\.");
                    filePojo.setType(temp[temp.length-1]);
                 String tempNames[] =  filePojo.getName().split("\\.");
                  String tempName = filePojo.getName().substring(0,filePojo.getName().lastIndexOf("."));
                 filePojo.setName(tempName);
                    //name = temp[0].substring(temp[0].lastIndexOf("/"),temp[0].length());
                    //filePojo.setName(name);
                    filePojo.setSuffix(temp[temp.length-1]);
                    filePojo.setIsImg(false);
                }else{
                    filePojo.setType("dir");
                    filePojo.setIsDir(true);
                }
                filePojos.add(filePojo);
            }
        }
        return filePojos;
    }


    @Override
    public Map<String, Object> getDirs(String id) {
        Map<String, Object> map = new HashMap<>();
        //List<FilePojo> filePojos = selectParentList(id);
        StringBuilder dir = new StringBuilder(CommonConstant.DIR_SPLIT);
        StringBuilder dirIds = new StringBuilder(CommonConstant.DIR_SPLIT);
        dir.append(id);
        dirIds.append(id);
       /* if (!CollectionUtils.isEmpty(filePojos)) {
            for (FilePojo filePojo : filePojos) {
                dir.append().append(CommonConstant.DIR_SPLIT);
                dirIds.append(filePojo.getId()).append(CommonConstant.DIR_SPLIT);
            }
        }*/
        map.put("dirs", dir.length() > 0 ? dir.deleteCharAt(dir.length() - 1).toString() : "");
        map.put("dirIds", dirIds.length() > 0 ? dirIds.deleteCharAt(dirIds.length() - 1).toString() : "");
        return map;
    }

    @Override
    public Boolean deleteObject(String dataId) {
        logger.info("要删除的文件路径为{}",dataId);
        if(dataId.indexOf(".")>-1 && !dataId.substring(dataId.length()-1,dataId.length()).equals("/")){  //文件删除
            return storageFileUtil.deleteObject(dataId);
        }else{  // TODO: 2021/12/8  文件夹删除
          return  storageFileUtil.deleteExamFolder(dataId);
           // return storageFileUtil.deleteFolder(dataId);
        }

    }

    @Override
    public void info() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        long startTime = System.currentTimeMillis();
        File file = new File("folderInfo.txt");
        FileOutputStream fop = null;
        try {
            fop = new FileOutputStream(file);
            String startStr = "开始计算文件大小"+sdf.format(new Date());
            fop.write(startStr.getBytes(StandardCharsets.UTF_8));
            fop.write("\n".getBytes(StandardCharsets.UTF_8));
            fop.write("文件名称\t\t\t文件数量\t\t\t文件大小\t\t\t\n".getBytes(StandardCharsets.UTF_8));
            List<String> stringList = storageFileUtil.bucketChild();
            for(String str : stringList){
                fop.write(str.getBytes(StandardCharsets.UTF_8));
                fop.write("\t\t\t\t".getBytes(StandardCharsets.UTF_8));
               Map<String,Object> map =  storageFileUtil.folderInfo(str);
               fop.write(map.get("count").toString().getBytes(StandardCharsets.UTF_8));
                fop.write("\t\t\t\t".getBytes(StandardCharsets.UTF_8));
                fop.write((map.get("size").toString()+"Mb").getBytes(StandardCharsets.UTF_8));
                fop.write("\n".getBytes(StandardCharsets.UTF_8));
            }
            String endStr = "结束计算文件大小"+sdf.format(new Date())+"\n";
            fop.write(endStr.getBytes(StandardCharsets.UTF_8));
            long endTime = System.currentTimeMillis();
            String temp = "计算文件大小共耗时"+(endTime-startTime)+"毫秒";
            fop.write(temp.getBytes(StandardCharsets.UTF_8));
            fop.flush();

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fop.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    @Override
    public void singleInfo(String prefix) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");

        String str = sdf1.format(new Date());
        long startTime = System.currentTimeMillis();
        File file = new File(prefix+"-"+str+".txt");
        FileOutputStream fop = null;
        try {
            fop = new FileOutputStream(file);
            String startStr = "开始计算文件大小"+sdf.format(new Date());
            fop.write(startStr.getBytes(StandardCharsets.UTF_8));
            fop.write("\n".getBytes(StandardCharsets.UTF_8));
            fop.write("文件名称\t\t\t文件数量\t\t\t文件大小\t\t\t\n".getBytes(StandardCharsets.UTF_8));
            List<String> stringList = storageFileUtil.bucketChild();
            prefix = prefix+"/";
                fop.write(prefix.getBytes(StandardCharsets.UTF_8));
                fop.write("\t\t\t\t".getBytes(StandardCharsets.UTF_8));
                Map<String,Object> map =  storageFileUtil.folderInfo(prefix);
                fop.write(map.get("count").toString().getBytes(StandardCharsets.UTF_8));
                fop.write("\t\t\t\t".getBytes(StandardCharsets.UTF_8));
                fop.write((map.get("size").toString()+"Mb").getBytes(StandardCharsets.UTF_8));
                fop.write("\n".getBytes(StandardCharsets.UTF_8));

            String endStr = "结束计算文件大小"+sdf.format(new Date())+"\n";
            fop.write(endStr.getBytes(StandardCharsets.UTF_8));
            long endTime = System.currentTimeMillis();
            String temp = "计算文件大小共耗时"+(endTime-startTime)+"毫秒";
            fop.write(temp.getBytes(StandardCharsets.UTF_8));
            fop.flush();

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fop.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private List<FilePojo> selectParentList(String parentId){
        List<FilePojo> filePojoList = new ArrayList<>();
        List<String> fileNameList = storageFileUtil.listChild(parentId);
      if(null != fileNameList && fileNameList.size()>0){
          for(String str : fileNameList){
              FilePojo filePojo = new FilePojo();
              filePojo.setName(str);
              filePojo.setId(str);
              filePojoList.add(filePojo);
          }
      }
      return filePojoList;

    }
}
